<template>
<div>
  <h1>单元信息</h1>
  <div class="divTop" v-model="search">
    <span>单元名称</span><el-input v-model="search.unitName" style="width: 250px" placeholder="请输入单元名称"></el-input>
    <span>单元编号</span><el-input v-model="search.unitCode" style="width: 250px" placeholder="请输入单元编号"></el-input>
    <span>是否有电梯</span><el-select v-model="search.unitHaveElevator" placeholder="请选择是否有电梯">
    <el-option label="是" value="1"></el-option>
    <el-option label="否" value="0"></el-option>
  </el-select>
    <span>楼栋</span>
    <el-select v-model="search.buildingId" placeholder="请选择楼栋">
      <el-option
          v-for="item in buildings"
          :key="item.buildingId"
          :label="item.buildingName"
          :value="item.buildingId">
      </el-option>
    </el-select>
    <p>
      <el-button @click="searchDJ" type="success" size="small" icon="el-icon-search">搜索</el-button>
      <el-button @click="searchCZ" size="small" icon="el-icon-refresh">重置</el-button>
    </p>
  </div>
  <!--  中层按钮-->
  <div>
    <el-row class="but-add">
      <el-button type="primary" size="small" @click="doAdd('unit')">添加</el-button>
      <el-button type="success" size="small" disabled>修改</el-button>
      <el-button type="danger" size="small" @click="deleteUnits" :disabled="isDisabled">批量删除</el-button>
      <el-button type="warning" size="small" @click="derive">导出</el-button>
    </el-row>
  </div>
  <!--  数据展示-->
  <el-table
      :data="units"
      :cell-style="{'text-align':'center'}"
      :header-cell-style="{background:'#E4E7ED','text-align':'center',color:'#000'}"
      @select="selectRoleOneId"
      @select-all="selectRoleAllIds"
      style="width: 100%">
    <el-table-column type="selection"></el-table-column>
    <el-table-column
        type="index"
        label="序号"
        width="100">
    </el-table-column>
    <el-table-column
        prop="communityName"
        label="小区名称"
        width="180">
    </el-table-column>
    <el-table-column
        prop="buildingName"
        label="楼栋名"
        width="150">
    </el-table-column>
    <el-table-column
        prop="unitName"
        label="单元名称"
        width="150">
    </el-table-column>
    <el-table-column
        prop="unitLevel"
        label="层数"
        width="180">
    </el-table-column>
    <el-table-column
        prop="unitAcreage"
        label="建筑面积"
        width="180">
    </el-table-column>
    <el-table-column
        prop="unitHaveElevator"
        label="是否有电梯">
      <template slot-scope="scop">
        <span v-if="scop.row.unitHaveElevator == '0'">否</span>
        <span v-if="scop.row.unitHaveElevator == '1'">是</span>
      </template>
    </el-table-column>
    <el-table-column
        prop="createTime"
        label="创建时间"
        width="200">
    </el-table-column>
    <el-table-column
        prop="remark"
        label="备注"
        width="200">
    </el-table-column>
    <el-table-column
        label="操作">
      <template slot-scope="scope">
        <el-button @click="doEdit(scope.row)" type="text" size="small">修改</el-button>
        <el-button @click="deleteUnit(scope.row.unitId)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  分页-->
  <div class="block">
    <el-pagination
        @size-change="sizeTo"
        @current-change="pageTo"
        :current-page="page"
        :page-sizes="[1,5,20, 30, 40]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="sizes">
    </el-pagination>
    <!--  添加或修改弹窗-->
    <el-dialog title="单元信息" width="500px" :visible.sync="unit_window">
      <el-form :model="unit" :rules="rules" ref="unit" label-width="100px" class="demo-ruleForm">
        <el-form-item label="楼栋">
          <el-select v-model="unit.buildingId" placeholder="请选择楼栋">
            <el-option
                v-for="item in buildings"
                :key="item.buildingId"
                :label="item.buildingName"
                :value="item.buildingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元名称" prop="unitName">
          <el-input v-model="unit.unitName"></el-input>
        </el-form-item>
        <el-form-item label="单元编号" prop="unitCode">
          <el-input v-model="unit.unitCode"></el-input>
        </el-form-item>
        <el-form-item label="层数" prop="unitLevel">
          <el-input v-model="unit.unitLevel"></el-input>
        </el-form-item>
        <el-form-item label="建筑面积" prop="unitAcreage">
          <el-input v-model="unit.unitAcreage"></el-input>
        </el-form-item>
        <el-form-item label="是都有电梯">
          <el-radio-group v-model="unit.unitHaveElevator">
            <el-radio :label="1" >是</el-radio>
            <el-radio :label="0" >否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="unit.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save('unit')">确认</el-button>
          <el-button @click="unit_window=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</div>
</template>

<script>
import {saveAs} from "file-saver";
export default {
  data(){
    return{
      units:[],
      pages:1,
      page:1,
      size:5,
      sizes:0,
      //批量删除或导出装ID的容器
      deleteList:[],
      isDisabled:true,
      unit:{"unitId":null,"communityId":"","buildingId":"","unitName":"","unitCode":"","unitLevel":"","unitAcreage":"","unitHaveElevator":"","createBy":"","createTime":"","updateBy":"","updateTime":"","remark":""},
      unit_window:false,
      buildings:[],
      rules:{
        buildingId:[{required: true, message: '楼栋不能为空', trigger: 'blur' }],
        unitName:[{required: true, message: '单元名不能为空', trigger: 'blur' }],
        unitLevel:[{required: true, message: '层数不能为空', trigger: 'blur' }],
      },
      //搜索实体
      search:{unitName:null,unitCode:null,unitHaveElevator:null,buildingId:null,comId:null}

    }
  },
  methods:{
    selectUnitAll(page,size){
      this.page=page;
      this.size=size;
      this.search.comId=localStorage.getItem("comId");
      console.log(this.search);
      this.$axios.post("/zyUnit/selectUnitAll/"+page,{
        size:this.size,
        unitName:this.search.unitName,
        unitCode:this.search.unitCode,
        unitHaveElevator:this.search.unitHaveElevator,
        buildingId:this.search.buildingId,
        comId:this.search.comId
      })
          .then(result =>{
            if (result.data.code==200){
              this.units=result.data.data.records;
              this.sizes=result.data.data.total;
              this.pages=result.data.data.pages;
            }
          })
    },
    //页码刷新
    pageTo(val){
      this.selectUnitAll(val,this.size);
      this.page=val;
    },
    //条数刷新
    sizeTo(val){
      this.selectUnitAll(this.page,val);
      console.log(val)
      this.size=val;
    },
    //获取多行数据
    selectRoleOneId(val){
      this.deleteList=[];
      for (let i = 0; i < val.length; i++) {
        this.deleteList[i]=val[i].unitId;
      }
      console.log(this.deleteList)
      this.deletesBut();
    },
    //获取全部行数据
    selectRoleAllIds(val){
      this.deleteList=[];
      for (let i = 0; i < val.length; i++) {
        this.deleteList[i]=val[i].unitId;
      }
      console.log(this.deleteList)
      this.deletesBut();
    },
    //判断批量删除按钮
    deletesBut(){
      if (this.deleteList.length>1){
        this.isDisabled = false;
      }else {
        this.isDisabled = true;
      }
    },
    selectBuildingAll(){
      this.$axios.get("/zyBuilding/selectBuildingAlls")
          .then(result =>{
            if (result.data.code==200){
              this.buildings = result.data.data;
              console.log(result.data.data)
            }
          })
    },
    //添加打开弹窗前的初始化操作
    doAdd(unit){
      this.unit={"unitId":null,"communityId":"","buildingId":"","unitName":"","unitCode":"","unitLevel":"","unitAcreage":"","unitHaveElevator":"","createBy":"","createTime":"","updateBy":"","updateTime":"","remark":""};
      this.selectBuildingAll();
      this.unit_window=true;
      this.$refs[unit].resetFields();
    },
    //修改前的初始化操作
    doEdit(unit){
      this.unit=JSON.parse(JSON.stringify(unit));
      console.log(unit)
      //判断电梯
      if (unit.unitHaveElevator == '0'){
        this.unit.unitHaveElevator=0;
      }else {
        this.unit.unitHaveElevator=1;
      }
      this.selectBuildingAll();
      this.unit_window = true;
    },
    //添加或修改
    save(unit){
      if (this.unit.unitId==null){//添加
        this.$refs[unit].validate((valid) => {
          if (valid) {
            // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
            this.unit.createBy=localStorage.getItem("username");//测试给默认值后续删
            this.$axios.post("/zyUnit/unitAdd",this.unit)
                .then(result =>{
                  if (result.data.code==200){
                    this.unit_window = false;
                    this.selectUnitAll(this.page,this.size);
                    this.$message({
                      message: '恭喜你，'+result.data.data,
                      type: 'success'
                    });
                  }else {
                    this.$message({
                      message: '警告哦，'+result.data.message,
                      type: 'warning'
                    });
                  }
                })
          } else {
            console.log("没写完")
            return false;
          }
        });

      }else {//修改
        // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
        this.unit.updateBy=localStorage.getItem("username");//测试给默认值后续删
        this.$axios.put("/zyUnit/unitEdit",this.unit)
            .then(result =>{
              if (result.data.code==200){
                this.unit_window = false;
                this.selectUnitAll(this.page,this.size);
                this.$message({
                  message: '恭喜你，'+result.data.data,
                  type: 'success'
                });
              }else {
                this.$message({
                  message: '警告哦，'+result.data.message,
                  type: 'warning'
                });
              }
            })
      }
    },
    //删除
    deleteUnit(unitId){
      this.$confirm('是否删除该单元信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(()=>{
        this.$axios.delete("/zyUnit/unitDelete/"+unitId)
            .then(result =>{
              if (result.data.code==200){
                if (this.units.length==1 && this.page>1){
                  this.selectUnitAll(this.page-1,this.size);
                }else {
                  this.selectUnitAll(this.page,this.size);
                }
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
              }
            })
      }).catch(() => {
        this.selectUnitAll(this.page,this.size);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除点击事件
    deleteUnits(){
      this.$confirm('此操作将删除多个单元，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(()=>{
        this.$axios.delete("/zyUnit/deleteUnits?unitIds="+this.deleteList)
            .then(result =>{
              if (result.data.code==200){
                if (this.units.length==1 && this.page>1){
                  this.selectUnitAll(this.page-1,this.size);
                }else if (this.deleteList.length == this.units.length) {
                  this.selectUnitAll(this.page-1,this.size);
                }else {
                  this.selectUnitAll(this.page,this.size);
                }
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
                this.deleteList=[];
                this.isDisabled=true;
              }
            })
      }).catch(() => {
        this.selectUnitAll(this.page,this.size);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //导出
    derive(){
      this.$prompt('请输入导出文件名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$axios.get("/zyUnit/derive?unitIds="+this.deleteList,{responseType: 'arraybuffer'})
            .then(result =>{
              const blob = new Blob([result.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
              saveAs(blob, value + '.xlsx');
              this.selectUnitAll(this.page,this.size);
              this.$message({
                type: 'success',
                message: '文件：'+value+'导出成功！'
              });
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导出！'
        });
      });
    },
    //搜索重置点击
    searchCZ(){
      this.search={unitName:null,unitCode:null,unitHaveElevator:null,buildingId:null};
      this.selectUnitAll(this.page,this.size);
    },
    //搜索点击
    searchDJ(){
      this.selectUnitAll(1,this.size);
    },


  },
  mounted() {
    this.selectUnitAll(this.page,this.size);
    this.selectBuildingAll();
  }
}
</script>

<style scoped lang="less">
.block{
  float: right;
  margin-right: 30px;
  margin-top: 30px;
}
.divTop{
  margin-bottom: 20px;
  text-align: left;
}
.divTop>span{
  margin-right: 10px;
  margin-left: 20px;
}
</style>